import React, { Component } from 'react';
import {
  Table,
  Checkbox,
  Button,
  Popover,
  Space,
  Modal,
  Select,
  Input,
  Form,
  Tabs,
} from 'antd';
import styles from './index.less';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

// 预设的函数模板
const FUNCTION_TEMPLATES = {
  simple: `// 可以使用 text(当前字段值) 和 record(整行数据) 
return text;`,
  withColor: `// 根据数值显示不同颜色
const value = Number(text);
if (value > 30) {
  return { type: 'text', style: { color: 'red' }, content: text };
}
return { type: 'text', style: { color: 'green' }, content: text };`,
  combineFields: `// 组合多个字段
return { type: 'text', content: record.name + ' - ' + record.age };`,
  conditional: `// 条件渲染
if (record.age > 30) {
  return { type: 'text', style: { fontWeight: 'bold' }, content: text };
}
return { type: 'text', content: text };`,
};

export default class CustomTable extends Component {
  formRef = React.createRef();

  state = {
    columns: [
      { title: '姓名', dataIndex: 'name', key: 'name' },
      { title: '年龄', dataIndex: 'age', key: 'age' },
      { title: '地址', dataIndex: 'address', key: 'address' },
      { title: '电话', dataIndex: 'phone', key: 'phone' },
      { title: '邮箱', dataIndex: 'email', key: 'email' },
    ],
    visibleColumns: ['name', 'age', 'address', 'phone', 'email'],
    dataSource: [
      {
        key: '1',
        name: '张三',
        age: 32,
        address: '北京市朝阳区',
        phone: '13800138000',
        email: 'zhangsan@example.com',
      },
      {
        key: '2',
        name: '李四',
        age: 28,
        address: '上海市浦东新区',
        phone: '13900139000',
        email: 'lisi@example.com',
      },
    ],
    customRenders: {},
    isCustomRenderModalVisible: false,
    currentEditColumn: null,
    renderFunctionError: null,
  };

  toggleColumn = columnKey => {
    const { visibleColumns } = this.state;
    if (visibleColumns.includes(columnKey)) {
      this.setState({
        visibleColumns: visibleColumns.filter(key => key !== columnKey),
      });
    } else {
      this.setState({
        visibleColumns: [...visibleColumns, columnKey],
      });
    }
  };

  getColumnSettingsContent = () => {
    const { columns, visibleColumns } = this.state;
    return (
      <div className={styles.columnSettings}>
        {columns.map(column => (
          <div key={column.key} className={styles.columnItem}>
            <Space>
              <Checkbox
                checked={visibleColumns.includes(column.key)}
                onChange={() => this.toggleColumn(column.key)}
              >
                {column.title}
              </Checkbox>
              <Button
                type="link"
                size="small"
                onClick={() => this.showCustomRenderModal(column)}
              >
                自定义渲染
              </Button>
            </Space>
          </div>
        ))}
      </div>
    );
  };

  showCustomRenderModal = column => {
    this.setState({
      isCustomRenderModalVisible: true,
      currentEditColumn: column,
      renderFunctionError: null,
    });
  };

  handleCustomRenderModalOk = values => {
    const { currentEditColumn, customRenders } = this.state;
    const { renderType, prefix, suffix, link, customFunction } = values;

    // 如果是自定义函数，先测试是否可用
    if (renderType === 'function') {
      try {
        // eslint-disable-next-line no-new-func
        const testFunc = new Function('text', 'record', customFunction);
        const result = testFunc('test', this.state.dataSource[0]);

        // 验证返回值格式
        if (typeof result === 'object' && !result.type) {
          throw new Error('函数返回值必须包含 type 属性');
        }
      } catch (error) {
        this.setState({
          renderFunctionError: `函数语法错误: ${error.message}`,
        });
        return;
      }
    }

    this.setState({
      customRenders: {
        ...customRenders,
        [currentEditColumn.key]: {
          type: renderType,
          prefix: prefix || '',
          suffix: suffix || '',
          link: link || '',
          customFunction: customFunction || '',
        },
      },
      isCustomRenderModalVisible: false,
      currentEditColumn: null,
      renderFunctionError: null,
    });
  };

  handleCustomRenderModalCancel = () => {
    this.setState({
      isCustomRenderModalVisible: false,
      currentEditColumn: null,
      renderFunctionError: null,
    });
  };

  // 渲染自定义返回的内容
  renderCustomContent = config => {
    const { type, style = {}, content, href } = config;

    switch (type) {
      case 'text':
        return <span style={style}>{content}</span>;
      case 'link':
        return (
          <a href={href || '#'} style={style}>
            {content}
          </a>
        );
      default:
        return content;
    }
  };

  generateCustomRender = (text, record, customRender) => {
    if (!customRender) return text;

    const { type, prefix, suffix, link, customFunction } = customRender;
    let content = text;

    // 如果是自定义函数
    if (type === 'function' && customFunction) {
      try {
        // eslint-disable-next-line no-new-func
        const renderFunc = new Function('text', 'record', customFunction);
        const result = renderFunc(text, record);

        // 如果返回的是对象，说明是自定义渲染配置
        if (typeof result === 'object' && result !== null) {
          return this.renderCustomContent(result);
        }
        return result;
      } catch (error) {
        console.error('自定义渲染函数执行错误:', error);
        return <span style={{ color: 'red' }}>渲染错误</span>;
      }
    }

    if (prefix) content = `${prefix}${content}`;
    if (suffix) content = `${content}${suffix}`;

    switch (type) {
      case 'text':
        return content;
      case 'link':
        return <a href={link || '#'}>{content}</a>;
      case 'bold':
        return <strong>{content}</strong>;
      case 'highlight':
        return <span style={{ backgroundColor: '#fff566' }}>{content}</span>;
      default:
        return content;
    }
  };

  getVisibleColumns = () => {
    const { columns, visibleColumns, customRenders } = this.state;
    return columns
      .filter(col => visibleColumns.includes(col.key))
      .map(col => ({
        ...col,
        render: (text, record) =>
          this.generateCustomRender(text, record, customRenders[col.key]),
      }));
  };

  handleTemplateSelect = template => {
    this.formRef.current?.setFieldsValue({
      customFunction: FUNCTION_TEMPLATES[template],
    });
  };

  renderCustomRenderModal = () => {
    const {
      isCustomRenderModalVisible,
      currentEditColumn,
      renderFunctionError,
    } = this.state;
    if (!currentEditColumn) return null;

    return (
      <Modal
        title={`自定义渲染 - ${currentEditColumn.title}`}
        open={isCustomRenderModalVisible}
        onCancel={this.handleCustomRenderModalCancel}
        footer={null}
        width={800}
      >
        <Form
          ref={this.formRef}
          onFinish={this.handleCustomRenderModalOk}
          layout="vertical"
          initialValues={{
            renderType: 'text',
          }}
        >
          <Form.Item
            name="renderType"
            label="渲染类型"
            rules={[{ required: true, message: '请选择渲染类型' }]}
          >
            <Select>
              <Option value="text">普通文本</Option>
              <Option value="link">链接</Option>
              <Option value="bold">加粗</Option>
              <Option value="highlight">高亮</Option>
              <Option value="function">自定义函数</Option>
            </Select>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.renderType !== currentValues.renderType
            }
          >
            {({ getFieldValue }) => {
              const renderType = getFieldValue('renderType');
              if (renderType === 'function') {
                return (
                  <>
                    <Form.Item label="函数模板">
                      <Select
                        placeholder="选择一个函数模板"
                        onChange={this.handleTemplateSelect}
                      >
                        <Option value="simple">简单返回</Option>
                        <Option value="withColor">条件着色</Option>
                        <Option value="combineFields">组合字段</Option>
                        <Option value="conditional">条件渲染</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item
                      name="customFunction"
                      label="自定义渲染函数"
                      rules={[{ required: true, message: '请输入自定义函数' }]}
                      help={
                        <div>
                          <div>可用参数:</div>
                          <div>text: 当前字段值</div>
                          <div>record: 当前行数据对象</div>
                          <div>返回格式示例:</div>
                          <div>{`{ type: 'text', style: { color: 'red' }, content: '内容' }`}</div>
                          {renderFunctionError && (
                            <div className={styles.errorText}>
                              {renderFunctionError}
                            </div>
                          )}
                        </div>
                      }
                    >
                      <TextArea
                        rows={10}
                        placeholder="输入自定义渲染函数，需要包含 return 语句"
                        className={styles.functionEditor}
                      />
                    </Form.Item>
                  </>
                );
              }

              return (
                <>
                  <Form.Item name="prefix" label="前缀">
                    <Input placeholder="输入要添加的前缀" />
                  </Form.Item>

                  <Form.Item name="suffix" label="后缀">
                    <Input placeholder="输入要添加的后缀" />
                  </Form.Item>

                  {renderType === 'link' && (
                    <Form.Item name="link" label="链接地址">
                      <Input placeholder="请输入链接地址" />
                    </Form.Item>
                  )}
                </>
              );
            }}
          </Form.Item>

          <Form.Item>
            <Space className={styles.modalFooter}>
              <Button onClick={this.handleCustomRenderModalCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  render() {
    return (
      <div className={styles.tableContainer}>
        <div className={styles.tableHeader}>
          <Space>
            <Popover
              title="列设置"
              trigger="click"
              content={this.getColumnSettingsContent()}
              placement="bottomLeft"
            >
              <Button>列设置</Button>
            </Popover>
          </Space>
        </div>
        <Table
          columns={this.getVisibleColumns()}
          dataSource={this.state.dataSource}
          {...this.props.tableProps}
        />
        {this.renderCustomRenderModal()}
      </div>
    );
  }
}
